package com.tron.sync.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tron.sync.entities.JZOrg;
import com.tron.sync.entities.OAOrg;
import com.tron.sync.entities.Operator;
import com.tron.sync.entities.PartyOrg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 更新用户，组织数据到SYNDA
 */
@Service
@Slf4j
public class SyndaServiceImpl {
    @Value("${syndaUrl}")
    private String syndaUrl;

    @Value("${client_id}")
    private String client_id;

    @Value("${client_secret}")
    private String client_secret;

    @Value("${username}")
    private String username;

    @Value("${password}")
    private String password;

    @Autowired
    JZOrgService jzOrgService;

    /**
     * 机构数据同步
     * @param partyOrg
     * @return
     */
    public  int syndOrgData(PartyOrg partyOrg){
        RestTemplate restTemplate = new RestTemplate();
        //   String uri = "http://192.168.9.99:15100/org/save";
        String object = restTemplate.postForObject(syndaUrl, partyOrg, String.class);
        log.info("请求平台数据===========================响应:"+object);
        JSONObject jsonObject = JSONObject.parseObject(object);
        int state = (int) jsonObject.get("state");
        if (state==200){
            JSONObject variables = jsonObject.getJSONObject("variables");
            String id = variables.getString("id");
            log.info(id);
            return 200;
        }
        return  500;
    }


    /**
     * 根据机构名称获取机构id，如果机构不存在则创建机构
     * @param orgName
     * @return
     */
    public String getOrgIdByName(String  orgName) {
        //如果机构
        if (!StringUtils.hasText(orgName)) {
            JZOrg byName = jzOrgService.getByName("其他机构");
            if (byName != null && StringUtils.hasText(byName.getId())) {
                return byName.getId();
            }
            JZOrg jzOrg = new JZOrg();
            jzOrg.setName("其他机构");
            jzOrg.setOrgParentId("ORG_ROOT");
            jzOrg.setOrgParentName("云南省公安厅");
            jzOrgService.save(jzOrg);
            return jzOrg.getId();
        }
        JZOrg byName = jzOrgService.getByName(orgName);
        if (byName != null && StringUtils.hasText(byName.getId())) {
            return byName.getId();
        }
        JZOrg jzOrg = new JZOrg();
        jzOrg.setName(orgName);
        jzOrg.setOrgParentId("ORG_ROOT");
        jzOrg.setOrgParentName("云南省公安厅");
        jzOrgService.save(jzOrg);
        return jzOrg.getId();
    }

    public  String saveOrg(OAOrg org){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("X-Authorization-access_token",getToken());
        httpHeaders.add("Content-Type","application/json;charset=UTF-8");
        HttpEntity<OAOrg> httpEntity = new HttpEntity<>(org,httpHeaders);
        ResponseEntity<String> exchange = restTemplate.exchange(syndaUrl+"/ibps/platform/v3/org/save", HttpMethod.POST, httpEntity, String.class);
        System.out.println("平台返回信息================="+exchange);
        JSONObject jsonObject = JSONObject.parseObject(exchange.getBody());
        String  id = "";
        if (jsonObject!=null&& jsonObject.getInteger("state")==200){
            id = jsonObject.getJSONObject("variables").getString("id");
        }
        if (jsonObject!=null&& jsonObject.getInteger("state")==599){
            log.error("拼音码重复，重新添加");
            org.setOrgAlias(org.getOrgAlias()+UUID.randomUUID().toString().substring(0,5));
            id=  saveOrg(org);
        }
        return id;
    }


    public  String saveOperator(Operator operator){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("partyEmployeePo",operator);
        jsonObject.put("user",operator);
        jsonObject.put("positionVoList",new JSONArray()) ;// 数组
        jsonObject.put("roleVoList",new JSONArray()) ;// 数组
        jsonObject.put("attrValueVoList",new JSONArray()) ;// 数组
        jsonObject.put("userGroupPoList",new JSONArray()) ;// 数组
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("X-Authorization-access_token",getToken());
        HttpEntity<Object> httpEntity = new HttpEntity<>(jsonObject,httpHeaders);
        ResponseEntity<String> exchange = restTemplate.exchange(syndaUrl+"/ibps/platform/v3/employee/create", HttpMethod.POST, httpEntity, String.class);
        System.out.println("创建用户返回信息======================"+exchange);
        JSONObject response = JSONObject.parseObject(exchange.getBody());
        String  id = "";
        if (response!=null&& response.getInteger("state")==200){
            id = response.getJSONObject("variables").getString("id");
        }
        return id;
    }

    public String getToken() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("client_id",client_id);
        map.put("client_secret",client_secret);
        map.put("grant_type","password_credentials");
        map.put("username",username);
        map.put("password",password);
        HttpEntity<Object> httpEntity = new HttpEntity<>(map);
        RestTemplate restTemplate = new RestTemplate();
        String object = restTemplate.postForObject(syndaUrl + "/ibps/oauth2/v3/authentication/apply", httpEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(object);
        Integer state = jsonObject.getInteger("state");
        if (state == 200) {
            JSONObject data = jsonObject.getJSONObject("data");
            String accessToken = data.getString("access_token");
            return accessToken;
        }
        return "";
    }

    public List<Map<String, String>> getOrgList() {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("X-Authorization-access_token",getToken());
        httpHeaders.add("Content-Type","application/json;charset=UTF-8");
        HttpEntity<OAOrg> httpEntity = new HttpEntity<>(httpHeaders);
        ResponseEntity<String> exchange = restTemplate.exchange(syndaUrl + "/ibps/platform/v3/org/findAll", HttpMethod.GET, httpEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(exchange.getBody());
        ArrayList<Map<String, String>> maps = new ArrayList<>();
        if (jsonObject.getInteger("state") == 200) {
            JSONArray data = jsonObject.getJSONArray("data");
            data.forEach(e->{
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1 = (JSONObject) e;
                HashMap<String, String> map = new HashMap<>();
                map.put("id", jsonObject1.getString("id"));
                map.put("parentId", jsonObject1.getString("parentId"));
                map.put("name", jsonObject1.getString("name"));
                maps.add(map);
            });
        }
        return maps;
    }

    public List<Map<String, String>> getFirstFloorByName(String orgName) {
        Assert.hasText(orgName, "机构名称不能为空");
        List<Map<String, String>> orgList = getOrgList();
        List<Map<String, String>> mapList = orgList.stream().filter(e -> {
            String parentId = e.get("parentId");
            String name = e.get("name");
            if ("ORG_ROOT".equals(parentId) && orgName.equals(name)) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        if (mapList.size() <= 0) {
            return null;
        }
        return mapList;
    }


    //根据机构名称获取用户列表
    public List<Map<String, String>> getUserListByOrg(String orgId) {
        /**
         * {
         *   "parameters": [
         *     {
         *       "key": "Q^GROUP_ID_^S",
         *       "value": "ORG_ROOT"
         *     }
         *   ]
         * }
         */
        HashMap<String, Object> map = new HashMap<>();
        HashMap<String, Object> parameters = new HashMap<>();
        parameters.put("key","Q^GROUP_ID_^S");
        parameters.put("value", orgId);
        map.put("parameters", Arrays.asList(parameters));
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("X-Authorization-access_token",getToken());
        httpHeaders.add("Content-Type","application/json;charset=UTF-8");
        HttpEntity<Object> httpEntity = new HttpEntity<>(map,httpHeaders);
        ResponseEntity<String> exchange = restTemplate.exchange(syndaUrl + "/ibps/platform/v3/employee/query", HttpMethod.POST, httpEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(exchange.getBody());
        ArrayList<Map<String, String>> maps = new ArrayList<>();
        if (jsonObject.getInteger("state") == 200) {
            JSONObject data = jsonObject.getJSONObject("data");
            JSONArray dataResult = data.getJSONArray("dataResult");
            dataResult.forEach(e->{
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1 = (JSONObject) e;
                String name = jsonObject1.getString("name");
                String account = jsonObject1.getString("account");
                String groupID = jsonObject1.getString("groupID");
                String id = jsonObject1.getString("id");
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("id", id);
                hashMap.put("name", name);
                hashMap.put("cardNo", account);
                hashMap.put("orgId", groupID);
                maps.add(hashMap);
            });
        }
        return maps;
    }

}
